package com.geek.enhnce.plugin.manager;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class DefaultSpringPluginFactory implements SpringPluginFactory, ApplicationContextAware, InitializingBean {
	static {
		BASE_DIR = System.getProperty("user.home") + "/.plugins/";
	}

	private static final String BASE_DIR;
	private ApplicationContext applicationContext; // 应用上下文
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public void activePlugin(String pluginId) {

	}

	@Override
	public void disablePlugin(String pluginId) {

	}

	@Override
	public void installPlugin(PluginConfig plugin, Boolean load) {

	}

	@Override
	public void uninstallPlugin(PluginConfig plugin) {

	}

	@Override
	public List<PluginConfig> getPluginList() {
		try {
			return new ArrayList<>(readerLocalConfigs().values());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("插件获取失败", e);
		}
	}

	/**
	 * 读取本地配置
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public Map<String, PluginConfig> readerLocalConfigs() throws Exception {
		String baseDir = BASE_DIR;
		File configFile = new File(baseDir + "PluginConfigs.obj");
		if (!configFile.exists()) {
			return null;
		}
		InputStream in = new FileInputStream(configFile);
		ObjectInputStream input;
		Map<String, PluginConfig> result = null;
		try {
			input = new ObjectInputStream(in);
			result = (Map<String, PluginConfig>) input.readObject();
		} finally {
			in.close();
		}
		return result;
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {

	}
}
